package org.yan.kangaroo.auth.config.security.handler;

import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.yan.kangaroo.auth.constant.response.ResponseCodeEnum;
import org.yan.kangaroo.auth.service.UserAuthService;
import org.yan.kangaroo.auth.service.UserLoginHistoryService;
import org.yan.kangaroo.common.response.ResponseUtils;
import org.yan.kangaroo.common.response.Result;
import org.yan.kangaroo.common.util.ip.IpInfoResult;
import org.yan.kangaroo.common.util.ip.IpLocationInfoResultVO;
import org.yan.kangaroo.common.util.ip.IpUtils;
import org.yan.kangaroo.pojo.ucenter.entity.UserAuth;
import org.yan.kangaroo.pojo.ucenter.entity.UserLoginHistory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证成功登录处理
 *
 * @author wangx
 * @date 11/08/2019 23:08
 */
@Slf4j
@Component
public class McpAuthenticationFailHandler implements AuthenticationFailureHandler {
    @Value("${tencent.location.key}")
    private String key;

    @Autowired
    private UserAuthService userAuthService;

    @Autowired
    private UserLoginHistoryService userLoginHistoryService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        log.warn("[onAuthenticationFailure] 用户登录失败:", exception);
        String username = request.getParameter("username");
        UserAuth userAuth = userAuthService.findByIdentifier(username);
        if (userAuth != null) {
            UserLoginHistory userLoginHistory = new UserLoginHistory();
            userLoginHistory.setAccountId(userAuth.getAccountId());
            userLoginHistory.setLoginMethod(userAuth.getIdentityType());
            userLoginHistory.setStatus(Boolean.FALSE);
            String ip = IpUtils.getIpAddress(request);
            userLoginHistory.setIp(ip);
            String originUserAgent = request.getHeader("User-Agent");
            UserAgent userAgent = UserAgent.parseUserAgentString(originUserAgent);
            userLoginHistory.setUserAgent(originUserAgent);
            userLoginHistory.setBrowser(userAgent.getBrowser().getName());
            userLoginHistory.setOperatorSystem(userAgent.getOperatingSystem().getName());
            IpLocationInfoResultVO ipLocationInfoResultVO = IpUtils.getIpAddressInfo(ip, key);
            if (ipLocationInfoResultVO == null) {
                log.info("[onAuthenticationFailure] 登录位置信息获取失败");
                userLoginHistoryService.localLoginInsert(userLoginHistory);
            } else {
                log.info("[onAuthenticationFailure] 登录位置信息获取成功");
                IpInfoResult result = ipLocationInfoResultVO.getResult();
                userLoginHistory.setNation(result.getAdInfo().getNation());
                userLoginHistory.setProvince(result.getAdInfo().getProvince());
                userLoginHistory.setCity(result.getAdInfo().getCity());
                userLoginHistory.setDistrict(result.getAdInfo().getDistrict());
                userLoginHistory.setAdcode(Integer.parseInt(result.getAdInfo().getAdcode()));
                userLoginHistory.setLat(result.getLocation().getLat());
                userLoginHistory.setLng(result.getLocation().getLng());
                userLoginHistoryService.insert(userLoginHistory);
            }
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ResponseUtils.outAsJson(response, Result.error(ResponseCodeEnum.USERNAME_OR_PASSWORD_ERROR));
    }
}
